package com.company.server;

import com.company.constant.Constant;

import java.io.DataOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Map;
import java.util.concurrent.*;

public class Server {
    public static Map<Socket, String> allOnlineUsers = new ConcurrentHashMap<>(); // 存储所有在线用户，将类型改为 ConcurrentHashMap，以保证线程安全
    // 将每个 Socket 对应的 DataOutputStream 缓存起来，减少服务端的线程发送数据时重复创建数据流的开销
    public static Map<Socket, DataOutputStream> allOnlineUsersOutputStream = new ConcurrentHashMap<>();
    public static void main(String[] args) {
        try {
            ServerSocket server = new ServerSocket(Constant.SERVER_PORT);
            ExecutorService pool = new ThreadPoolExecutor(5, 10, 5, TimeUnit.SECONDS,
                    new ArrayBlockingQueue<Runnable>(100), new ThreadPoolExecutor.AbortPolicy());
            // 主线程 一直等待客户端的连接
            while (true) {
                System.out.println("等待客户端的连接中...");
                Socket client = server.accept();
                // 将连接上的客户端 Socket 管道交给线程池处理
                Runnable task = new ServerThread(client);
                pool.execute(task);
                System.out.println("一个客户端连接成功...");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
